package org.example.exp2.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

@Service
public class ApiService {

    private final WebClient webClient;

    @Autowired
    public ApiService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.baseUrl("http://localhost:8090").build();
    }

    public String callGetApi(String url, MediaType responseType) {
        return webClient.get()
                .uri(url)
                .accept(responseType)
                .retrieve()
                .bodyToMono(String.class)
                .block(); // Block to get the result synchronously
    }

    public String callPostApi(String url, Object request, MediaType responseType) {
        return webClient.post()
                .uri(url)
                .body(Mono.just(request), Object.class)
                .accept(responseType)
                .retrieve()
                .bodyToMono(String.class)
                .block(); // Block to get the result synchronously
    }

    public String callPutApi(String url, Object request, MediaType responseType) {
        return webClient.put()
                .uri(url)
                .body(Mono.just(request), Object.class)
                .accept(responseType)
                .retrieve()
                .bodyToMono(String.class)
                .block(); // Block to get the result synchronously
    }

    public String callDeleteApi(String url, MediaType responseType) {
        return webClient.delete()
                .uri(url)
                .accept(responseType)
                .retrieve()
                .bodyToMono(String.class)
                .block(); // Block to get the result synchronously
    }
}